var express = require('express');
var router = express.Router();
const alipaySdk = require('../utils/alipayConfig');
const axios = require('axios')
const istoken = require('../utils/token');
const userDataModel = require('../model/userDataModel');
const FBDataModel = require('../model/FBmodel');
/* 支付 */
router.post('/alipayFB', istoken, async (req, res, next) => {
    const { id, money, data } = req.body
    //订单数据
    const bizContent = {
        out_trade_no: id,
        total_amount: money,
        subject: data,
        product_code: 'FAST_INSTANT_TRADE_PAY',
    }
    //创建订单
    const result = await alipaySdk.pageExecute('alipay.trade.page.pay', 'GET', { bizContent, returnUrl: 'http://localhost:5174/FBalipay' });
    res.json({ code: '200', data: result })
});

/* 支付回调-------------------------------------------------- */
router.post('/isAlipayFB', async (req, res, next) => {
    const { out_trade_no, trade_no, mail } = req.body
    //订单数据
    const bizContent = {
        out_trade_no,
        trade_no
    }
    //发送支付宝axios
    const result = await alipaySdk.pageExecute('alipay.trade.query', 'GET', { bizContent });
    const data = await axios({ url: result, method: "get" })
    const datares = data.data.alipay_trade_query_response
    if (datares.code === '10000') {
        switch (datares.trade_status) {
            case 'TRADE_SUCCESS':
                const userMail = await userDataModel.findOne({ _id: mail })
                const newdata = await FBDataModel.findOne({ _id: out_trade_no })
                console.log(newdata);
                res.json({ code: '200', data: '支付成功' })
                break;
            case 'TRADE_FINISHED':
                res.json({ code: '200', data: '支付成功,不可退款' })
                break;
            case 'WAIT_BUYER_PAY':
                res.json({ code: '300', data: '等待付款' })
                break;
            case 'TRADE_CLOSED':
                res.json({ code: '404', data: '未付款交易超时关闭' })
                break;
        }
    }
});

module.exports = router;
